package com.dp.mallchat.common.user.dao;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dp.mallchat.common.user.domain.entity.UserApply;
import com.dp.mallchat.common.user.domain.user.enums.UserApplyEnum;
import com.dp.mallchat.common.user.domain.user.enums.UserApplyReadStatusEnum;
import com.dp.mallchat.common.user.domain.user.enums.UserApprovalStatusEnum;
import com.dp.mallchat.common.user.mapper.UserApplyMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 用户申请表 服务实现类
 * </p>
 *
 * @author <a href="https://gitee.com/baiDP">adu</a>
 * @since 2024-06-19
 */
@Service
public class UserApplyDao extends ServiceImpl<UserApplyMapper, UserApply>{

    public Page<UserApply> listByUid(Long uid, Page page) {
        return lambdaQuery()
                .eq(UserApply::getTargetId, uid)
                .eq(UserApply::getType, UserApplyEnum.ADD_FRIEND.getType())
                .orderByDesc(UserApply::getCreateTime)
                .page(page);
    }

    public void updateReadStatus(List<Long> ids) {
        lambdaUpdate()
                .set(UserApply::getReadStatus, UserApplyReadStatusEnum.READ.getType())
                .eq(UserApply::getReadStatus, UserApplyReadStatusEnum.UN_READ.getType())
                .in(UserApply::getId, ids)
                .update();
    }

    public Integer countUnRead(Long uid) {
        return lambdaQuery()
                .eq(UserApply::getUid, uid)
                .eq(UserApply::getType, UserApplyEnum.ADD_FRIEND.getType())
                .eq(UserApply::getStatus, UserApprovalStatusEnum.UN_PASS.getStatus())
                .eq(UserApply::getReadStatus, UserApplyReadStatusEnum.UN_READ.getType())
                .count();
    }

    public UserApply selectById(Long uid, Long targetUid, Integer type, Integer status) {
        return lambdaQuery()
                .eq(UserApply::getUid, uid)
                .eq(UserApply::getTargetId, targetUid)
                .eq(UserApply::getType, type)
                .eq(UserApply::getStatus, status)
                .one();
    }

    public void updateStatus(Long uid, Long targetUid, Integer status1, Integer status2) {
        lambdaUpdate()
                .set(UserApply::getStatus, status2)
                .eq(UserApply::getId, uid)
                .eq(UserApply::getTargetId, targetUid)
                .eq(UserApply::getStatus, status1)
                .update();
    }

    public void agree(Long applyId) {
        lambdaUpdate()
                .set(UserApply::getStatus, UserApprovalStatusEnum.PASS.getStatus())
                .eq(UserApply::getId, applyId)
                .update();
    }

    public Integer getUnReadCount(Long targetId) {
        return lambdaQuery().eq(UserApply::getTargetId, targetId)
                .eq(UserApply::getReadStatus, UserApplyReadStatusEnum.UN_READ.getType())
                .count();
    }
}
